package com.heze.xunhuan.controller;

import com.heze.xunhuan.entity.Post;
import com.heze.xunhuan.service.AdminService;
import com.heze.xunhuan.utils.SecurityContextUtil;
import com.heze.xunhuan.vo.PageVO;
import com.heze.xunhuan.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 管理后台控制器
 *
 * @author heze-xunhuan
 */
@Tag(name = "系统管理", description = "管理后台相关接口")
@RestController
@RequestMapping("/api/v1/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminService adminService;

    @Operation(summary = "平台数据概览", description = "获取平台数据统计概览")
    @GetMapping("/dashboard/overview")
    public Result<Map<String, Object>> getDashboardOverview() {
        Map<String, Object> overview = adminService.getDashboardOverview();
        return Result.success(overview);
    }

    @Operation(summary = "待审核信息列表", description = "获取待审核的信息列表")
    @GetMapping("/posts/pending")
    public Result<PageVO<Post>> getPendingPosts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        PageVO<Post> pageVO = adminService.getPendingPosts(page, size);
        return Result.success(pageVO);
    }

    @Operation(summary = "审核信息", description = "审核信息（通过或拒绝）")
    @PostMapping("/posts/{id}/audit")
    public Result<Void> auditPost(
            @PathVariable Long id,
            @RequestBody Map<String, String> params) {
        Long adminUserId = SecurityContextUtil.getCurrentUserId();
        if (adminUserId == null) {
            return Result.unauthorized("未登录");
        }

        // 参数校验
        String action = params.get("action");
        if (action == null || action.trim().isEmpty()) {
            return Result.badRequest("审核操作不能为空");
        }

        // 验证action值是否合法
        if (!"approve".equals(action) && !"reject".equals(action)) {
            return Result.badRequest("审核操作只能是approve或reject");
        }

        String reason = params.get("reason");
        adminService.auditPost(id, adminUserId, action, reason);
        return Result.success();
    }
}

